package demo06;

import java.util.Arrays;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author: WangPeng
 * @createTime: 2022/11/01 17:23
 * @description: 手动锁
 * @version: v1.0
 */
public class ManualLock {
    private static String[] arr = new String[2];
    private static int index = 0;
    public static void main(String[] args) {
        //创建锁对象
        Lock lock = new ReentrantLock();

        Thread thread1 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //加锁
                    lock.lock();
                    if (arr[index] == null){
                        arr[index] = "hello";
                        index++;
                    }
                }finally {
                    //释放锁，因为加锁后一定需要释放锁，所以要写在finally里
                    lock.unlock();
                }
            }
        });
        Thread thread2 = new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    //加锁
                    lock.lock();
                    if (arr[index] == null){
                        arr[index] = "java";
                        index++;
                    }
                }finally {
                    //释放锁，因为加锁后一定需要释放锁，所以要写在finally里
                    lock.unlock();
                }
            }
        });
        thread1.start();
        thread2.start();
        //不能直接打印arr,因为main线程可能先获取cpu
        try {
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(Arrays.toString(arr));
    }
}